import {ref, onMounted, onUnmounted} from 'vue'
import {
    usePreviewFitScale,
    usePreviewScrollYScale,
    usePreviewScrollXScale,
    usePreviewFullScale
} from './usePreviewScale.hook'

export const useScale = (scaleType: string, screenWidth: number, screenHeight: number) => {

    const previewRef = ref()
    const entityRef = ref()
    const width = ref(screenWidth)
    const height = ref(screenHeight)

    // 屏幕适配
    onMounted(() => {
        if (scaleType == 'fit') {
            const {calcRate, windowResize, unWindowResize} = usePreviewFitScale(
                width.value as number,
                height.value as number,
                previewRef.value,
            )
            calcRate()
            windowResize()
            onUnmounted(() => {
                unWindowResize()
            })
        } else if (scaleType == 'scrollY') {
            const {calcRate, windowResize, unWindowResize} = usePreviewScrollYScale(
                width.value as number,
                height.value as number,
                previewRef.value,
                (scale) => {
                    const dom = entityRef.value
                    dom.style.width = `${width.value * scale.width}px`
                    dom.style.height = `${height.value * scale.height}px`
                }
            )
            calcRate()
            windowResize()
            onUnmounted(() => {
                unWindowResize()
            })
        } else if (scaleType == 'scrollX') {
            const {calcRate, windowResize, unWindowResize} = usePreviewScrollXScale(
                width.value as number,
                height.value as number,
                previewRef.value,
                (scale) => {
                    const dom = entityRef.value
                    dom.style.width = `${width.value * scale.width}px`
                    dom.style.height = `${height.value * scale.height}px`
                }
            )
            calcRate()
            windowResize()
            onUnmounted(() => {
                unWindowResize()
            })
        } else if (scaleType == 'full') {
            const {calcRate, windowResize, unWindowResize} = usePreviewFullScale(
                width.value as number,
                height.value as number,
                previewRef.value,
            )
            calcRate()
            windowResize()
            onUnmounted(() => {
                unWindowResize()
            })
        }

    })

    return {
        entityRef,
        previewRef
    }
}
